package com.koron.common.core.business.langfield.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.koron.bean.base.Response;
import com.koron.common.core.business.langfield.bean.LangFieldBean;
import com.koron.common.core.business.langfield.mapper.LangFieldBeanMapper;
import com.koron.common.core.util.CodeTools;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LangFieldService {

    @TaskAnnotation("addLangFiel")
    public Response addLangFiel(SessionFactory factory, LangFieldBean langfieldbean) {
        LangFieldBeanMapper mapper = factory.getMapper(LangFieldBeanMapper.class);

        // 1. 同一数据字典分类下，字典编码不能重复
        List<LangFieldBean> list = mapper.queryByFormKeyAndFieldKey(langfieldbean.getFormKey(), langfieldbean.getFieldKey(), null);
        Assert.isFalse(CollUtil.isNotEmpty(list), "同表单下字段不能重复");

        langfieldbean.setId(CodeTools.getCode32());
        mapper.insert(langfieldbean);
        return Response.success();
    }

    @TaskAnnotation("removeLangFiel")
    public Response removeLangFiel(SessionFactory factory, String id) {
        LangFieldBeanMapper mapper = factory.getMapper(LangFieldBeanMapper.class);
        mapper.deleteByPrimaryKey(id);
        return Response.success();
    }

    @TaskAnnotation("updateLangFiel")
    public Response updateLangFiel(SessionFactory factory, LangFieldBean langfieldbean) {
        LangFieldBeanMapper mapper = factory.getMapper(LangFieldBeanMapper.class);
        Assert.isFalse(StrUtil.isBlank(langfieldbean.getId()), "表单id不能为空");

        // 1. 同一数据字典分类下，字典编码不能重复
        List<LangFieldBean> list = mapper.queryByFormKeyAndFieldKey(langfieldbean.getFormKey(), langfieldbean.getFieldKey(), langfieldbean.getId());
        Assert.isFalse(CollUtil.isNotEmpty(list), "同表单下字段不能重复");

        mapper.updateByPrimaryKey(langfieldbean);
        return Response.success();
    }

    @TaskAnnotation("queryById")
    public Response queryById(SessionFactory factory, String id) {
        LangFieldBeanMapper mapper = factory.getMapper(LangFieldBeanMapper.class);
        LangFieldBean langFieldBean = mapper.selectByPrimaryKey(id);
        return Response.success(langFieldBean);
    }

}